import __config from '../../../config/env'
const app = getApp()

Page({
  data: {
    CustomBar: app.globalData.CustomBar,
    theme: app.globalData.theme, //全局颜色变量
    version: app.globalData.version,
    config: app.globalData.config,
    // 1充值开启
    balanceIsEntrance: app.globalData.balanceIsEntrance,
    wxUser: null,
    userInfo: null,
    orderCountAll: [],
    orderTip: null
  },
  onShow() {
    //更新tabbar购物车数量
    // wx.setTabBarBadge({
    //   index: 2,
    //   text: app.globalData.shoppingCartCount + ''
    // })
    // this.setData({
    //   balanceIsEntrance: app.globalData.balanceIsEntrance
    // });

    let wxUser = app.globalData.wxUser
    this.setData({
      wxUser: wxUser
    })
    this.userInfoGet()
    this.orderCountAll()
    app.doLogin()
  },
  onLoad() {
    this.setData({
      theme: app.globalData.theme
    });
  },
  /**
   * 小程序设置
   */
  settings: function () {
    wx.openSetting({
      success: function (res) {
        console.log(res.authSetting)
      }
    })
  },
  onChooseAvatar(e) {
    const that = this
    // 临时路径
    let avatarUrl = e.detail.avatarUrl
    // 上传头像到服务器
    wx.showLoading({
      title: '加载中',
    })
    wx.uploadFile({
      url: __config.basePath + '/mall/api/ma/file/upload',
      filePath: avatarUrl,
      header: {
        'app-id': wx.getAccountInfoSync().miniProgram.appId,
        'third-session': wx.getStorageSync('third_session') != null ? wx.getStorageSync('third_session') : ''
      },
      name: 'file',
      formData: {
        'fileType': 'image',
        'dir': 'userinfo/headimg/'
      },
      success(uploadFileRes) {
        if (uploadFileRes.statusCode == '200') {
          let link = JSON.parse(uploadFileRes.data).link
          app.api.userInfoPut({
            id: that.data.userInfo.id,
            headimgUrl: link
          }).then(res => {
            that.userInfoGet()
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '上传失败：' + uploadFileRes.data,
            success(res) {}
          });
        }
      },
      fail: (err) => {
        console.log(err)
      },
      complete(res) {
        wx.hideLoading()
      }
    })
  },
  onGetNickName(e) {
    let nickName = e.detail.value
    app.api.userInfoPut({
      id: this.data.userInfo.id,
      nickName: nickName
    }).then(res => {
      this.userInfoGet()
    })
  },
  //获取用户信息
  userInfoGet() {
    app.api.userInfoGet()
      .then(res => {
        this.setData({
          userInfo: res.data
        })
      })
  },
  orderCountAll() {
    app.api.orderCountAll()
      .then(res => {
        this.setData({
          orderCountAll: res.data
        })
        this.loadOrderTip()
      })
  },
  loadOrderTip() {
    if (this.data.orderCountAll[0] > 0 || this.data.orderCountAll[2] > 0) {
      let status = this.data.orderCountAll[2] > 0 ? 2 : 0
      // 获取施工中订单
      app.api.orderPage({
          searchCount: false,
          current: 1,
          size: 1,
          ascs: '', //升序字段
          descs: 'create_time',
          status: status
        })
        .then(res => {
          let orderList = res.data.records || []
          if (orderList.length > 0) {
            if (status == 0) {
              app.api.orderGet(orderList[0].id)
                .then(res1 => {
                  let orderInfo = res1.data
                  orderInfo.status = 0
                  this.setData({
                    orderTip: orderInfo
                  })
                })
            } else {
              this.setData({
                orderTip: orderList[0]
              })
            }
          }
        })
    }
  },
  orderTipClick() {
    let orderTip = this.data.orderTip
    if (orderTip) {
      if (orderTip.status == 0) {
        // 去支付
        wx.navigateTo({
          url: '/pages/order/order-detail/index?callPay=true&id=' + orderTip.id
        })
      } else if (orderTip.status == 2) {
        // 导航
        let expressSite = orderTip.expressSite
        if (expressSite) {
          wx.openLocation({
            longitude: Number.parseFloat(expressSite.longitude),
            latitude: Number.parseFloat(expressSite.latitude),
            name: expressSite.name
          })
        }
      }
    }
  },
  countDownDone() {
    this.orderCountAll()
  },
  handleContact() {
    wx.makePhoneCall({
      phoneNumber: '4008888888'
    })
  },
  jumpToProvider() {
    wx.navigateToMiniProgram({
      appId: 'wxdb48d3ba4e348290', // 要打开的小程序 appId
      // 打开的页面路径，如果为空则打开首页
      path: 'pages/home/index',
      extraData: {
        foo: 'bar' //需要传递给目标小程序的数据，目标小程序可在 App.onLaunch，App.onShow 中获取到这份数据
      },
      // 要打开的小程序版本。develop 开发版、trial 体验版、release 正式版。仅在当前小程序为开发版或体验版时此参数有效。如果当前小程序是正式版，则打开的小程序必定是正式版。
      envVersion: 'trial',
      success(res) {
        // 打开成功
      }
    })
  }
})